﻿using Duality;
using Duality.Components;
using Duality.Components.Renderers;
using OpenTK;

namespace ClientApp
{
	[RequiredComponent(typeof(Transform))]
	[RequiredComponent(typeof(AnimSpriteRenderer))]
	public class Splatter : Component, ICmpInitializable, ICmpUpdatable
	{
		private const float LifeTimeBase = 20000.0f;
		private float lifeTime = LifeTimeBase;
		private float creationTime;

		public float Progress
		{
			get { return (Time.GameTimer - creationTime) / lifeTime; }
		}
		public float BaseSize
		{
			get
			{
				AnimSpriteRenderer r = this.GameObj.Renderer as AnimSpriteRenderer;
				return (r.Rect.w + r.Rect.h) * 0.5f;
			}
			set
			{
				AnimSpriteRenderer r = this.GameObj.Renderer as AnimSpriteRenderer;
				r.Rect = Rect.AlignCenter(0.0f, 0.0f, value, value);
				lifeTime = LifeTimeBase * MathF.Pow(value / 128.0f, 1.5f);
			}
		}

		public void OnInit(Component.InitContext context)
		{
			creationTime = Time.GameTimer;
		}
		public void OnShutdown(Component.ShutdownContext context)
		{
		}

		void ICmpUpdatable.OnUpdate()
		{
			AnimSpriteRenderer renderer = this.GameObj.GetComponent<AnimSpriteRenderer>();
			Transform transform = this.GameObj.Transform;

			float progress = this.Progress;
			if (progress > 1.0f)
			{
				this.GameObj.DisposeLater();
			}
			else
			{
				transform.Scale = Vector3.One + Vector3.One * 0.15f * progress;
				renderer.ColorTint = renderer.ColorTint.WithAlpha(1.0f - progress);
			}
		}
	}
}
